package cn.edu.neu.lab603.cloudeval.monitor

import cn.edu.neu.lab603.cloudeval.CloudEval
import cn.edu.neu.lab603.cloudeval.entity.CloudTask
import cn.edu.neu.lab603.cloudeval.entity.CloudTask.SubmissionEvent
import cn.edu.neu.lab603.des.{SimMetric, SimMonitor}

import scala.collection.mutable

/** 云计算任务等待时间的监控器。
  *
  * Created by yfwz100 on 16/9/24.
  */
class CloudletWaitingTimeMetric extends SimMonitor[CloudEval] with SimMetric[Double] {

  /** 监控 Cloudlet 的映射。 */
  val stats = new mutable.HashMap[CloudTask, (Int, Int)]

  override def after(context: CloudEval): Unit = {}

  override def isMatch(context: CloudEval): Boolean = context.getCurrentTask.isInstanceOf[SubmissionEvent]

  override def before(context: CloudEval): Unit = {
    implicit val simulation = context
    for (cloudlet <- SubmissionEvent.getCurrentCloudlets) {
      val preVal = stats.get(cloudlet)
      if (preVal.isEmpty) {
        stats(cloudlet) = (context.getCurrentClock, -1)
      } else {
        stats(cloudlet) = (preVal.get._1, context.getCurrentClock)
      }
    }
  }

  def getWaitingTimeSum: Int = {
    if (stats.nonEmpty)
      stats.values.filter(_._2 > 0).map(p => p._2 - p._1 - 1).sum
    else 0
  }

  override def getCurrentValue: Double = getWaitingTimeSum
}
